import { fetchEventSource } from '@microsoft/fetch-event-source';
import { parseTime } from '@/utils/ruoyi';

const state = {
  messages: [
    {
      role: 'assistant',
      content: "您好！我是Gelly，您的智能检修助手。\n\n我可以帮助您：\n- 解答设备疑问\n- 提供检修建议\n- 分析故障数据\n- 解释复杂概念\n\n请问今天有什么可以帮您？",
      time: parseTime(new Date())
    }
  ],
  history: [],
  isTyping: false,
  error: null
};

const mutations = {
  ADD_MESSAGE: (state, message) => {
    state.messages.push(message);
  },
  UPDATE_LAST_MESSAGE: (state, payload) => {
    const lastMessage = state.messages[state.messages.length - 1];
    if (lastMessage && lastMessage.role === 'assistant') {
      for (const key in payload) {
        lastMessage[key] = payload[key];
      }
    }
  },
  SET_IS_TYPING: (state, isTyping) => {
    state.isTyping = isTyping;
  },
  SET_HISTORY: (state, history) => {
    state.history = history;
  },
  SET_ERROR: (state, error) => {
    state.error = error;
    // Only update the last message if a real error occurred.
    if (error) {
      const lastMessage = state.messages[state.messages.length - 1];
      if (lastMessage && lastMessage.role === 'assistant') {
        lastMessage.content = `抱歉，出现错误：${error}`;
        lastMessage.isThinkingComplete = true;
      }
      state.isTyping = false;
    }
  },
  CLEAR_CHAT: (state) => {
    state.messages = [];
    state.history = [];
    state.isTyping = false;
    state.error = null;
  },
  REMOVE_LAST_MESSAGES: (state, count) => {
    state.messages.splice(-count);
  }
};

const actions = {
  async sendMessage({ commit, state }, question) {
    const history = state.messages.filter(m => m.role === 'user' || (m.role === 'assistant' && m.content))
      .map(m => ({ role: m.role, content: m.content }));

    commit('SET_IS_TYPING', true);
    commit('SET_ERROR', null);

    // 添加页面可见性变化监听，确保后台时也能继续处理
    let isPageVisible = !document.hidden;
    const handleVisibilityChange = () => {
      isPageVisible = !document.hidden;
      console.log('页面可见性变化:', isPageVisible ? '可见' : '隐藏');
    };
    document.addEventListener('visibilitychange', handleVisibilityChange);

    const userMessage = {
      role: 'user',
      content: question,
      time: parseTime(new Date())
    };
    commit('ADD_MESSAGE', userMessage);

    const assistantMessage = {
      role: 'assistant',
      content: '',
      thinking_process: '',
      isThinkingComplete: false,
      time: parseTime(new Date())
    };
    commit('ADD_MESSAGE', assistantMessage);

    let mode = 'think';
    let buffer = '';

    try {
      await fetchEventSource('https://api.withoutend.top/chat/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'Connection': 'keep-alive'
        },
        body: JSON.stringify({ question, history }),
        // 添加保活机制，即使页面在后台也保持连接
        openWhenHidden: true,
        onopen: async (response) => {
          console.log('🔗 SSE连接已建立');
          if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`请求失败: ${response.status} - ${errorText}`);
          }
        },
        onmessage: (event) => {
          // 即使页面在后台，也要处理消息
          console.log('📨 收到SSE消息，页面状态:', document.hidden ? '后台' : '前台');

          if (event.data === '[DONE]') {
            console.log('✅ AI输出完成');
            commit('SET_IS_TYPING', false);
            // 清理事件监听器
            document.removeEventListener('visibilitychange', handleVisibilityChange);
            return;
          }

          let data;
          try {
            data = JSON.parse(event.data);
          } catch (e) {
            console.warn('⚠️ 解析SSE数据失败:', e);
            return; // Ignore parsing errors for now
          }

          if (data.error) throw new Error(data.error);

          buffer += data.token;
          let newContent = {};

          if (mode === 'think') {
            const thinkStartTag = '<think>';
            const thinkEndTag = '</think>';
            let displayThinkProcess = buffer.startsWith(thinkStartTag) ? buffer.substring(thinkStartTag.length) : buffer;
            const thinkEndIndex = displayThinkProcess.indexOf(thinkEndTag);

            if (thinkEndIndex !== -1) {
              newContent.thinking_process = displayThinkProcess.substring(0, thinkEndIndex);
              newContent.isThinkingComplete = true;
              mode = 'answer';
              const remaining = displayThinkProcess.substring(thinkEndIndex + thinkEndTag.length);
              if (remaining) {
                 newContent.content = (state.messages[state.messages.length - 1].content + remaining.replace(/^\s+/, ''));
              }
            } else {
              newContent.thinking_process = displayThinkProcess;
            }
          } else {
             newContent.content = state.messages[state.messages.length - 1].content + data.token;
          }
          commit('UPDATE_LAST_MESSAGE', newContent);
        },
        onerror: (err) => {
          console.error('❌ SSE连接错误:', err);
          console.log('页面状态:', document.hidden ? '后台' : '前台');

          // 清理事件监听器
          document.removeEventListener('visibilitychange', handleVisibilityChange);

          // 如果是因为页面在后台导致的连接问题，给出更友好的提示
          if (document.hidden) {
            commit('SET_ERROR', 'AI正在后台继续处理，请稍候...');
            // 可以考虑在这里添加重连逻辑
          } else {
            commit('SET_ERROR', '与服务器的连接出现问题。');
          }
          throw err;
        }
      });
    } catch (error) {
      console.error('💥 发送消息失败:', error);
      // 清理事件监听器
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      commit('SET_ERROR', error.message || '发生未知错误');
    }
  },

  regenerateLastAnswer({ dispatch, commit, state }) {
    const lastUserMessageIndex = state.messages.findLastIndex(m => m.role === 'user');
    if (lastUserMessageIndex !== -1) {
        const lastUserMessage = state.messages[lastUserMessageIndex];

        // Remove the last user message and the assistant's response
        commit('REMOVE_LAST_MESSAGES', state.messages.length - lastUserMessageIndex);

        // Remove last Q/A from history
        const newHistory = [...state.history];
        if (newHistory.length >= 2) {
          newHistory.splice(-2);
        }
        commit('SET_HISTORY', newHistory);

        dispatch('sendMessage', lastUserMessage.content);
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
